# -*- coding: utf-8 -*-
import os
import collections
from datetime import datetime
import glob

PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

def all_file_path(root_dictory,extension_name):
    '''
    遍历文件目录
    :param root_dictory:
    :param extension_name:
    :return:
    '''
    file_dic=collections.OrderedDict()
    for parent,dirnames,filenames in os.walk(root_dictory):
        for filename in filenames:
            if 'filter' not in filename:
                filename=filename.encode("utf-8")
                if filename.endswith(extension_name):
                    path=os.path.join(parent.encode("utf-8"),filename).replace('\\','/')
                    file_dic[filename]=path
    return file_dic

def get_sub_dir_files(root_dir,extension_name):
    '''
    获取制定目录下子目录的制定格式文件
    :param root_dir:  目录名
    :param extension_name: 后缀名
    :return:
    '''
    files=glob.glob(root_dir+"/*/"+extension_name)
    return files
    pass


def save_content(content):
    path=os.path.dirname(os.path.join(os.path.dirname(__file__)))+'/TestResult'
    filepath=get_new_folder(path)+'/log'
    if not os.path.exists(filepath):
        os.mkdir(filepath)
    filepath=filepath+'/outPut1.log'
    save(content,filepath)


def save(content,filepath):
    cur_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with open(filepath, 'a+') as f:
        result = cur_time + '------' + content + '\n'
        f.write(result)

def get_new_folder(test_report):
    '''
    获取最新文件夹下
    :param test_report:
    :return:
    '''
    lists = os.listdir(test_report)                                    #列出目录的下所有文件和文件夹保存到lists
    lists.sort(key=lambda fn:os.path.getmtime(test_report + "/" + fn))#按时间排序
    file_new =test_report+'/'+lists[-1]                   #获取最新的文件保存到file_new
    # print(file_new)
    return file_new


def remove_file(f):
    try:
        if os.path.isfile(f):
            os.remove(f)
        else:
            print("%s文件不存在，无法删除" % f)
    except Exception as e:
        print("删除文件异常",str(e))

def remove_folder(path):
    ls = os.listdir(path)
    #如果目录不为空，则清空目录下文件
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            remove_folder(c_path)
        else:
            remove_file(c_path)
    #最后删除目录
    os.rmdir(path)


if __name__=="__main__":
    # test_report="E:/python/project/FFAutoTest/Config"#目录地址
    # path = os.path.dirname(os.path.join(os.path.dirname(__file__))) + '/TestResult'
    # get_new_folder(path)
    # # new_report(test_report)
    # save_content('hello,workd2')
    remove_folder("E:\\python\\project\\FFAutoTest\\TestResult\\192-168-1-105-5555\\2018-10-18_16_23_2788")